<template>
  <tm-app>
    <tm-navbar title="连接Wifi" :followTheme="true" :hideHome="false">
    </tm-navbar>
    <ad unit-id="adunit-fe0e8ef4e679c31e" ad-type="video" ad-theme="white"></ad>
    <tm-alert
      :followTheme="true"
      :maxLine="2"
      :margin="[20, 40, 20, 20]"
      :content="content2"
      :height="140"
      linearDeep="accent"
      linear="right"
    ></tm-alert>
    <tm-sheet
      :round="4"
      :padding="[20, 100]"
      height="100%"
      :margin="[20]"
      _class="flex flex-col flex-col-center-center "
      :style="{ height: 'calc(100% - 44px)' }"
    >
      <tm-sheet
        :round="24"
        :padding="[0]"
        :shadow="10"
        :followTheme="true"
        @click="startAdd"
      >
        <view class="start-btn flex flex-col flex-col-center-center">
          <tm-icon
            :name="
              !state.linkStatus ? 'tmicon-paperplane-fill' : 'tmicon-check'
            "
            :fontSize="50"
          ></tm-icon>
          <tm-text
            _class="mt-n4 text-weight-b"
            :fontSize="34"
            :label="state.linkStatus ? '连接成功' : '点击连接'"
          ></tm-text>
        </view>
      </tm-sheet>
    </tm-sheet>
    <tm-message ref="msg" :lines="5"></tm-message>
    <tm-modal
      title="Wifi连接失败"
      okText="复制并关闭"
      v-model:show="state.linkFail"
      @cancel="state.linkFail = false"
      @ok="copyWifiPassword(2)"
    >
      <tm-input
        v-model="state.wifiInfo.wifiName"
        prefixLabel="WIFI账号"
        :margin="[0, 24]"
      ></tm-input>
      <tm-input
        v-model="state.wifiInfo.wifiPassword"
        prefixLabel="WIFI密码"
        :margin="[0, 24]"
      >
        <template v-slot:right>
          <tm-icon name="tmicon-copy" @click="copyWifiPassword"></tm-icon>
        </template>
      </tm-input>
    </tm-modal>
  </tm-app>
</template>

<script setup>
import { onLoad, onReady } from "@dcloudio/uni-app";
import { reactive, ref } from "vue";
import { useTmpiniaStore } from "@/tmui/tool/lib/tmpinia";
import { getWifiCodeInfoApi, addConnectionRecordApi } from "@/api";
import { jumpAppId } from "@/config";

const store = useTmpiniaStore();
const state = reactive({
  wifiInfo: {},
  //   wifi初始化状态
  initWifiStatus: false,
  // 连接状态
  linkStatus: false,
  // 系统类别 ios android
  platform: uni.getSystemInfoSync().platform,
  // userCode
  userCode: "",
  timer: null,
  // 链接失败
  linkFail: false,
  // 在页面中定义激励视频广告
  videoAd: null,
  // 广告是否看完
  addShowEnd: false,
});
const content2 = ref([
  {
    title: "系统提示",
    content: "点击连接，视频播放完后自动连接",
  },
]);
const msg = ref(null);

onLoad(async ({ scene }) => {
  console.log(scene, 1111111111);
  store.setTmVuetifyTheme("indigo");
  let wifiCodeId = "4151400174547";
  try {
    wifiCodeId = decodeURIComponent(scene).split("=")[1];
  } catch (error) {
    uni.showToast({
      icon: "error",
      title: "二维码错误,请联系负责人",
    });
  }
  getWifiCodeInfoApi({
    wifiCodeId,
  }).then((res) => {
    state.wifiInfo = res;
    if (!res.merchantName) {
      uni.redirectTo({
        url: "/homePages/createWifi?id=" + res.id.toString(),
      });
    }
  });
  // 只有失败才初始化
  uni.startWifi({
    success: () => {
      state.initWifiStatus = true;
      uni.onWifiConnected(async () => {
        if (state.platform == "ios") {
          console.log("ios ====> 连接成功");
          const promotionUrl = state.wifiInfo.promotionUrl;
          if (!promotionUrl) {
            uni.switchTab({
              url: "/pages/shop/shop",
            });
          } else {
            navigatorToMiniProgram(state.wifiInfo.promotionUrl);
          }
        }
      });
    },
    fail: () => {
      state.initWifiStatus = false;
      uni.showToast({
        icon: "error",
        title: "Wifi初始化失败,请重新扫码",
      });
    },
  });
});

const navigatorToMiniProgram = (path) => {
  if (!path) {
    return;
  }
  uni.navigateToMiniProgram({
    appId: jumpAppId,
    path,
    success: (res) => {},
    fail: () => {
      uni.switchTab({
        url: "/pages/shop/shop",
      });
    },
  });
};

onReady(() => {
  // 在页面onLoad回调事件中创建激励视频广告实例
  if (uni.createRewardedVideoAd) {
    state.videoAd = uni.createRewardedVideoAd({
      adUnitId: "adunit-4d5c1660eaf75418",
    });
    state.videoAd.onLoad(() => {});
    state.videoAd.onError((err) => {});
    state.videoAd.onClose(async (res) => {
      state.addShowEnd = res.isEnded;
      if (res.isEnded) {
        uni.login({
          provider: "weixin",
          success: async ({ code }) => {
            state.userCode = code;
            await addConnectionRecordApi({
              wifiId: state.wifiInfo.id,
              code: state.userCode,
            });
            linkWifi();
          },
        });
      } else {
        uni.showToast({
          icon: "error",
          title: "视频未播放完毕",
        });
      }
    });
  }
});

const startAdd = async () => {
  console.log(state.videoAd, state.addShowEnd);
  // 用户触发广告后，显示激励视频广告
  if (state.videoAd && !state.addShowEnd) {
    state.videoAd.show().catch(() => {
      // 失败重试
      state.videoAd
        .load()
        .then(() => state.videoAd.show())
        .catch((err) => {
          console.log("激励视频 广告显示失败");
        });
    });
  } else {
    linkWifi();
  }
};
/**
 *  0	ok	正常
    12000	not init	未先调用 startWifi 接口
    12001	system not support	当前系统不支持相关能力
    12002	password error Wi-Fi	密码错误
    12005	wifi not turned on	Android 特有，未打开 Wi-Fi 开关
    12013	wifi config may be expired	系统保存的 Wi-Fi 配置过期，建议忘记 Wi-Fi 后重试，仅 Android 支持
 */
const linkWifi = () => {
  if (state.wifiInfo.id && state.initWifiStatus) {
    uni.showToast({
      icon: "loading",
      title: "连接中",
      duration: 10000,
    });

    uni.connectWifi({
      SSID: state.wifiInfo.wifiName,
      password: state.wifiInfo.wifiPassword,
      success: async () => {
        uni.getConnectedWifi({
          partialInfo: true,
          fail: () => {
            state.linkFail = true;
          },
        });
        if (state.platform == "android") {
          console.log("android ====> 连接成功");
          const promotionUrl = state.wifiInfo.promotionUrl;
          if (!promotionUrl) {
            uni.switchTab({
              url: "/pages/shop/shop",
            });
          } else {
            navigatorToMiniProgram(state.wifiInfo.promotionUrl);
          }
        }
      },
      fail: (error) => {
        console.log(error);
        const { errCode } = error;
        const errObj = {
          12000: "未先调用 startWifi 接口",
          12001: "当前系统不支持相关能力",
          12002: "密码错误",
          12005: "未打开 Wi-Fi 开关",
          12013: "系统保存的 Wi-Fi 配置过期，建议忘记 Wi-Fi 后重试",
          12003: "连接超时",
          12004: "重复连接 Wi-Fi",
          12006: "未打开 GPS 定位开关",
          12007: "用户拒绝授权链接 Wi-Fi",
          12008: "无效WIFI,请联系管理员",
          12009: "系统运营商配置拒绝连接 Wi-Fi",
          12010: "系统其他错误，需要在 errmsg 打印具体的错误原因",
          12011: "应用在后台无法配置 Wi-Fi",
          12013: "系统保存的 Wi-Fi 配置过期，建议忘记 Wi-Fi 后重试",
          12014: "密码错误",
        };
        uni.showToast({
          icon: "error",
          title: errObj[errCode] || "连接失败，请复制wifi密码手动连接",
        });
        state.linkFail = true;
      },
      complete: () => {
        msg.value.hide();
      },
    });
  }
};

const copyWifiPassword = (type = 1) => {
  uni.setClipboardData({
    data: state.wifiInfo.wifiPassword,
    success: () => {
      uni.showToast({
        icon: "success",
        title: "复制成功,请打开手机设置进行连接",
      });
      if (type == 2) {
        state.linkFail = false;
      }
    },
    fail: () => {
      uni.showToast({
        icon: "error",
        title: "复制失败",
      });
    },
  });
};
</script>

<style scoped>
.custom-click {
  transition: all 400ms;
}
.custom-click:hover {
  transform: scale(1.04);
}
.start-btn {
  transition: all 100ms;
  padding: 20rpx;
  height: 155rpx;
  width: 155rpx;
  border-radius: 50%;
}
.start-btn:active {
  transform: scale(1.14);
  background-color: #673ab7;
}
</style>
